{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Federated Learning - SMS spam prediction with a GRU model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook, we will train a model using federated approach.\n",
    "\n",
    "**NOTE:** At the time of running this notebook, we were running the grid components in background mode.  \n",
    "\n",
    "**NOTE:**\n",
    "Components:\n",
    " - Grid Gateway(http://localhost:8080)\n",
    " - Grid Node Bob (http://localhost:3000)\n",
    " - Grid Node Anne (http://localhost:3001)\n",
    " \n",
    "To **start the gateway**:\n",
    "* ```cd gateway```\n",
    "* ```python gateway.py --start_local_db --port=5000```\n",
    "\n",
    "To **start one grid node**:\n",
    "\n",
    "* ```cd app/websocket/```\n",
    "\n",
    "* ```python websocket_app.py --start_local_db --id=alice --port=3001 --gateway_url=http://localhost:5000```\n",
    " \n",
    "This notebook was made based on [Federated SMS Spam prediction](https://github.com/OpenMined/PySyft/tree/master/examples/tutorials/advanced/Federated%20SMS%20Spam%20prediction).\n",
    "\n",
    "Authors:\n",
    "* André Macedo Farias: Github: [@andrelmfarias](https://github.com/andrelmfarias) | Twitter: [@andrelmfarias](https://twitter.com/andrelmfarias)\n",
    "* George Muraru: Github [@gmuraru](https://github.com/gmuraru) | Twitter: [@georgemuraru](https://twitter.com/georgemuraru) | Facebook: [@George Cristian Muraru](https://www.facebook.com/georgecmuraru)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Useful imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-06-14T22:55:56.381002Z",
     "start_time": "2019-06-14T22:55:52.562283Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import syft as sy\n",
    "from syft.grid.public_grid import PublicGridNetwork\n",
    "\n",
    "import torch as th\n",
    "from torch import optim\n",
    "\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Connecting to Grid Network"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "hook = sy.TorchHook(th)\n",
    "\n",
    "my_grid = PublicGridNetwork(hook, \"http://localhost:5000\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Seach a dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = my_grid.search(\"#X\", \"#spam\", \"#dataset\")\n",
    "target = my_grid.search(\"#Y\", \"#spam\", \"#dataset\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Bob': [(Wrapper)>[PointerTensor | me:96906351671 -> Bob:58176119719]\n",
       "  \tTags: #spam #X #dataset \n",
       "  \tShape: torch.Size([2786, 30])\n",
       "  \tDescription: The input datapoints to the SPAM dataset....],\n",
       " 'Alice': [(Wrapper)>[PointerTensor | me:91520735976 -> Alice:16627579692]\n",
       "  \tTags: #spam #X #dataset \n",
       "  \tShape: torch.Size([2786, 30])\n",
       "  \tDescription: The input datapoints to the SPAM dataset....]}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Bob': [(Wrapper)>[PointerTensor | me:52053241859 -> Bob:34347751563]\n",
       "  \tTags: #Y #spam #dataset \n",
       "  \tShape: torch.Size([2786])\n",
       "  \tDescription: The input labels to the SPAM dataset....],\n",
       " 'Alice': [(Wrapper)>[PointerTensor | me:44687882238 -> Alice:89030703951]\n",
       "  \tTags: #Y #spam #dataset \n",
       "  \tShape: torch.Size([2786])\n",
       "  \tDescription: The input labels to the SPAM dataset....]}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "target"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-06-03T19:33:42.613017Z",
     "start_time": "2019-06-03T19:33:42.598004Z"
    }
   },
   "outputs": [],
   "source": [
    "from handcrafted_GRU import GRU"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = list(data.values())\n",
    "target = list(target.values())\n",
    "\n",
    "VOCAB_SIZE = 0\n",
    "for data_comp in data:\n",
    "    VOCAB_SIZE = max(VOCAB_SIZE, int(data_comp[0].max().get()))\n",
    "    \n",
    "VOCAB_SIZE += 1\n",
    "HIDDEN_DIM = 10\n",
    "EMBEDDING_DIM = 50\n",
    "BATCH_SIZE = 128\n",
    "CLIP = 5 # gradient clipping - to avoid gradient explosion (frequent in RNNs)\n",
    "DROPOUT = 0.2\n",
    "EPOCHS = 15\n",
    "LR = 0.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-06-03T19:33:42.638046Z",
     "start_time": "2019-06-03T19:33:42.617601Z"
    }
   },
   "outputs": [],
   "source": [
    "\n",
    "# Initiating the model\n",
    "model = GRU(vocab_size=VOCAB_SIZE, hidden_dim=HIDDEN_DIM, embedding_dim=EMBEDDING_DIM, dropout=DROPOUT)\n",
    "\n",
    "# And the optimizer\n",
    "optimizer = optim.SGD(model.parameters(), lr=LR)\n",
    "\n",
    "# And the loss\n",
    "criterion = th.nn.BCELoss()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Perform train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-06-03T20:00:23.084933Z",
     "start_time": "2019-06-03T20:00:23.078688Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train Epoch: 0 [0/5572 (0%)]\tLoss: 12.313264\n",
      "Train Epoch: 0 [2786/5572 (50%)]\tLoss: 9.950761\n",
      "Train Epoch: 1 [0/5572 (0%)]\tLoss: 9.132653\n"
     ]
    }
   ],
   "source": [
    "import math # Needed for separating into batches\n",
    "\n",
    "def train(epoch):\n",
    "    dataset_size = sum([len(data[i][0]) for i in range(len(data))])\n",
    "    model.train()\n",
    "    \n",
    "    for i in range(len(data)):\n",
    "        loss_cum = 0\n",
    "        nr_batches = math.ceil(len(data[i][0]) / BATCH_SIZE)\n",
    "        for batch_idx in range(nr_batches):\n",
    "            # Extract the batch for training and target\n",
    "            data_batch = data[i][0][BATCH_SIZE * batch_idx : BATCH_SIZE * (batch_idx + 1), :]\n",
    "            target_batch = target[i][0][BATCH_SIZE * batch_idx : BATCH_SIZE * (batch_idx + 1)]\n",
    "            \n",
    "            # Send the model to the worker\n",
    "            worker = data_batch.location\n",
    "            model.send(worker)\n",
    "            h = th.Tensor(np.zeros((data_batch.shape[0], HIDDEN_DIM))).send(worker)\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            pred, _ = model(data_batch, h)\n",
    "            loss = criterion(pred.squeeze(), target_batch.float())\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            model.get()\n",
    "            \n",
    "            # Cumulate the loss\n",
    "            loss_cum += loss.get().item()\n",
    "        \n",
    "        print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n",
    "                epoch, i * data[i][0].shape[0], dataset_size,\n",
    "                       100. *  (i * data[i][0].shape[0]) / dataset_size, loss_cum))\n",
    "\n",
    "for epoch in range(EPOCHS):\n",
    "    train(epoch)"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
